// 病友圈详情
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { StarFill, LeftOutline, LikeOutline } from 'antd-mobile-icons'
import request from '../../api/request';
import './Detail.css';

interface SickCircleDetail {
  sickCircleId: number;
  authorUserId: number;
  departmentId: number;
  adoptFlag: number;
  title: string;
  department: string;
  disease: string;
  detail: string;
  treatmentHospital: string;
  treatmentStartTime: string;
  treatmentEndTime: string;
  treatmentProcess: string;
  picture: string;
  collectionFlag: number;
  collectionNum: number;
  commentNum: number;
  adoptNickName: string;
  adoptHeadPic: string;
  adoptComment: string;
  adoptTime: number;
}

interface DetailResponse {
  result: SickCircleDetail;
  message: string;
  status: string;
}

interface CommentItem {
  commentId: number;
  commentUserId: number;
  nickName: string;
  headPic: string;
  content: string;
  supportNum: number;
  opposeNum: number;
  opinion: number; // 1 赞同 2 反对
  whetherDoctor: number; // 是否为医生
  commentTime: number;
}

interface CommentListResponse {
  result: CommentItem[];
  message: string;
  status: string;
}

const SickCircleDetail = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [detail, setDetail] = useState<SickCircleDetail | null>(null);
  const [loading, setLoading] = useState(false);

  // 评论遮罩状态
  const [showComments, setShowComments] = useState(false);
  const [comments, setComments] = useState<CommentItem[]>([]);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentsPage] = useState(1);
  const COMMENTS_COUNT = 10;

  // 发表评论
  const [commentText, setCommentText] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (id) {
      fetchDetail();
    }
  }, [id]);

  const fetchDetail = async () => {
    try {
      setLoading(true);
      const res = await request.get('/health/user/sickCircle/v1/findSickCircleInfo', {
        params: { sickCircleId: id }
      }) as DetailResponse;

      console.log('详情res', res);

      if (res.result) {
        setDetail(res.result);
      }
    } catch (error) {
      console.error('获取详情失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  // 兼容后端返回的多种时间格式：毫秒时间戳/秒时间戳/已格式化字符串
  const formatDateValue = (value: unknown): string => {
    if (value === null || value === undefined) return '';
    if (typeof value === 'number') {
      // 10位认为是秒，13位认为是毫秒
      const ms = String(value).length === 10 ? value * 1000 : value;
      return formatTime(ms);
    }
    if (typeof value === 'string') {
      // 全数字：按时间戳解析；否则认为已是可读日期字符串
      if (/^\d{10,13}$/.test(value)) {
        const num = Number(value);
        const ms = value.length === 10 ? num * 1000 : num;
        return formatTime(ms);
      }
      return value;
    }
    return '';
  };

  const openComments = async () => {
    if (!detail) return;
    setShowComments(true);
    try {
      setCommentsLoading(true);
      const res = await request.get('/health/user/sickCircle/v1/findSickCircleCommentList', {
        params: {
          sickCircleId: detail.sickCircleId,
          page: commentsPage,
          count: COMMENTS_COUNT
        }
      }) as CommentListResponse;
      if (Array.isArray(res.result)) {
        setComments(res.result);
      } else {
        setComments([]);
      }
    } catch (error) {
      console.error('获取评论失败:', error);
      setComments([]);
    } finally {
      setCommentsLoading(false);
    }
  };

  const closeComments = () => setShowComments(false);

  const submitComment = async () => {
    if (!detail) return;
    const trimmed = commentText.trim();
    if (!trimmed) return;
    try {
      setSubmitting(true);
      const form = new URLSearchParams();
      form.append('sickCircleId', String(detail.sickCircleId));
      form.append('content', trimmed);
      // 一些后端需要同时在表单中携带 userId / sessionId
      const userId = localStorage.getItem('userId') || ''
      const sessionId = localStorage.getItem('sessionId') || ''
      if (userId) form.append('userId', userId)
      if (sessionId) form.append('sessionId', sessionId)
      await request.post('/health/user/sickCircle/verify/v1/publishComment', form, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
      });
      // 直接在前端追加一条评论（缺少返回id时，临时生成负id）
      const tempComment: CommentItem = {
        commentId: Date.now() * -1,
        commentUserId: 0,
        nickName: '我',
        headPic: '',
        content: trimmed,
        supportNum: 0,
        opposeNum: 0,
        opinion: 0,
        whetherDoctor: 0,
        commentTime: Date.now(),
      };
      setComments((prev) => [tempComment, ...prev]);
      setCommentText('');
    } catch (error) {
      console.error('发表评论失败:', error);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  if (!detail) {
    return <div className="error">数据加载失败</div>;
  }

  return (
    <div className="detail-page">
      {/* 顶部导航栏 */}
      <div className="nav-bar">
        <div className="back-button" onClick={handleBack}>
          <LeftOutline />
        </div>
        <div className="nav-title">{detail.title}</div>
      </div>

      {/* 主要内容 */}
      <div className="detail-content">
        {/* 主标题 */}
        <div className="main-title">{detail.title}</div>

        {/* 病症信息 */}
        <div className="info-section">
          <div className="section-title">[病症]</div>
          <div className="section-content">{detail.disease}</div>
        </div>

        {/* 科室信息 */}
        <div className="info-section">
          <div className="section-title">[科室]</div>
          <div className="section-content">{detail.department}</div>
        </div>

        {/* 病症详情 */}
        <div className="info-section">
          <div className="section-title">[病症详情]</div>
          <div className="section-content">{detail.detail}</div>
        </div>

        {/* 治疗经历 */}
        <div className="info-section">
          <div className="image-header">
            <div className="section-title">[治疗经历]</div>
            <div className="image-time">
              {detail.treatmentStartTime || detail.treatmentEndTime ?
                `${formatDateValue(detail.treatmentStartTime)} - ${formatDateValue(detail.treatmentEndTime)}` :
                ''}
            </div>
          </div>
          <div className="section-content">
            {detail.treatmentProcess || '暂无治疗经历'}
          </div>
        </div>

        {/* 相关图片 */}
        <div className="info-section">
          <div className="section-title">[相关图片]</div>
          {detail.picture && (
            <div className="image-container">
              <img src={detail.picture} alt="相关图片" className="detail-image" />
            </div>
          )}
          {/* 图片下方的交互栏 */}
          <div className="bottom-bar">
            <div className="interaction-item">
              <span className="star-icon">⭐{detail.collectionNum}</span>
            </div>
            <div className="interaction-item" onClick={openComments}>
              <span className="comment-icon"><StarFill />{detail.commentNum}</span>
            </div>
          </div>

          {detail.adoptComment && (
            <div className="adopt-box">
              <div className="adopt-title">被采纳的建议</div>
              <div className="adopt-content">{detail.adoptComment}</div>
            </div>
          )}
        </div>
      </div>

      {/* 评论遮罩层 */}
      {showComments && (
        <div className="comments-mask" onClick={closeComments}>
          <div className="comments-panel" onClick={(e) => e.stopPropagation()}>
            <div className="comments-body">
              {commentsLoading ? (
                <div className="comments-loading">加载中...</div>
              ) : (
                <div className="comments-list">
                  {comments.length === 0 ? (
                    <div className="no-comments">暂无评论</div>
                  ) : (
                    comments.map((c) => (
                      <div key={c.commentId} className="comment-item">
                        <img className="comment-avatar" src={c.headPic} alt="avatar" onClick={() => navigate(`/patient-circle/user/${c.commentUserId}`, { state: { nickName: c.nickName, headPic: c.headPic } })} />
                        <div className="comment-main">
                          <div className="comment-top">
                            <div className="comment-name">{c.nickName}</div>
                          </div>
                          <div className="comment-content">{c.content}</div>
                          <div className="comment-bottom">
                            <div className="comment-time">{formatTime(c.commentTime)}</div>
                            <div className="comment-actions">
                              <span className="comment-like"><LikeOutline /> {c.supportNum}</span>
                              <span className="comment-dislike"><LikeOutline style={{ transform: 'scaleY(-1) ' }} />{c.opposeNum}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))
                  )}
                </div>
              )}
            </div>
            <div className="comments-footer">
              <button className="comments-close-btn" onClick={closeComments} aria-label="close">×</button>
              <div className="comments-input">
                <input
                  className="comments-input-input"
                  placeholder="在此留下高见吧！！"
                  value={commentText}
                  onChange={(e) => setCommentText(e.target.value)}
                  disabled={submitting}
                />
                <button className="comments-send-btn" onClick={submitComment} disabled={submitting || !commentText.trim()}>
                  发布
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SickCircleDetail;